package com.menggudf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.menggudf.entity.Illness;

@Repository
public class IllnessDao{   

    private static final Log log = LogFactory.getLog(IllnessDao.class);

    @PersistenceContext(unitName = "medicalUnit")
    private EntityManager entityManager;

    public void persist(Illness transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(Illness persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public Illness merge(Illness detachedInstance) {
        try {
            Illness result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Illness findById(Long id) {
        try {
            Illness instance = entityManager.find(Illness.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List<Illness> getIllnessList(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge,
            int pageSize,
            int offset) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i ,Symptom s,AgeSelect a where i.id=s.illness and i.id=a.illness ");
            this.makeSql(sqld, illName, parts, levelOneSubject, levelTwoSubject, startTime, endTime, diseaseAge);
            if(!StringUtils.isEmpty(illName)){
                sqld.append(" and i.illness like:name");
            }
            if(!StringUtils.isEmpty(symptomName)){
                sqld.append(" and s.symptom='"+symptomName+"' ");
            }
            if(!StringUtils.isEmpty(parts)){
                sqld.append(" and s.parts='"+parts+"' ");
            }
            sqld.append(" order by i.createTime desc");
            Query query = entityManager.createQuery(sqld.toString()).setFirstResult(offset).setMaxResults(pageSize);
            if(!StringUtils.isEmpty(illName)){
                query.setParameter("name", "%"+illName+"%");
            }
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllnessList fail",e);
            throw e;
        }
    }

    public long getIllnessListCount(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge) {
        try {
            StringBuffer sqld = new StringBuffer("select count(distinct i) from Illness i ,Symptom s,AgeSelect a where i.id=s.illness and i.id=a.illness ");
            this.makeSql(sqld, illName, parts, levelOneSubject, levelTwoSubject, startTime, endTime, diseaseAge);
            if(!StringUtils.isEmpty(illName)){
                sqld.append(" and i.illness like:name");
            }
            if(!StringUtils.isEmpty(symptomName)){
                sqld.append(" and s.symptom='"+symptomName+"' ");
            }
            if(!StringUtils.isEmpty(parts)){
                sqld.append(" and s.parts='"+parts+"' ");
            }
            Query query = entityManager.createQuery(sqld.toString());
            if(!StringUtils.isEmpty(illName)){
                query.setParameter("name", "%"+illName+"%");
            }
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getIllnessListCount fail",e);
            throw e;
        }
    }
    
    private void makeSql(
            StringBuffer mysql,
            String illName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge){
        if(!StringUtils.isEmpty(diseaseAge)){
            mysql.append(" and a.ageOption in ("+diseaseAge+")");
        }
/*        if(!StringUtils.isEmpty(illName)){
            mysql.append(" and i.illness='"+illName+"' ");
        }*/
        if(!StringUtils.isEmpty(levelOneSubject)){
            mysql.append(" and i.levelOneSubject='"+levelOneSubject+"' ");
        }
        if(!StringUtils.isEmpty(levelTwoSubject)){
            mysql.append(" and i.levelTwoSubject='"+levelTwoSubject+"' ");
        }

        mysql.append(" and i.createTime>='"+startTime+"' and i.createTime<='"+endTime+"'");


    }

    public Illness getIllnessRecortByIllness(String illness) {
        try {
            StringBuffer sqld = new StringBuffer("from Illness i where i.illness=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, illness);
            List<Illness> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("getIllnessRecortByIllness fail",e);
            throw e;
        }
    }

    public List<Illness> getIllByparts(String parts) {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("unchecked")
    public List<Illness> getIllnessRecortByIds(String ids) {
        try {
            StringBuffer sqld = new StringBuffer("from Illness i where i.id in ("+ids+") ");
            Query query = entityManager.createQuery(sqld.toString());
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllnessRecortByIds fail",e);
            throw e;
        }
    }

    public List<Illness> getIllByIdAndsymptoms(
            String symptom,
            String ids,
            String temperature,
            String sYS,
            String dIA,
            String pulse,
            String degree,
            String nature,
            String times) {
        // TODO Auto-generated method stub
        return null;
    }

    public Illness getIllnessById(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    public List<Illness> getIllnessInParts(
            String parts,
            int sex,
            int isInjured,
            int diseaseAge,
            String temperature,
            String sYS,
            String dIA,
            String pulse,
            int type) {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("unchecked")
    public List<Illness> getIllnessBySexAndAge(Integer sex, Integer age) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,AgeSelect a where i.id=a.illness and a.ageOption=?1 ");
            if(sex!=null){
                sqld.append(" and i.sex in (?2,2) ");
            }else{
                sqld.append(" and i.sex in (2) ");
            }
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, age).setParameter(2, sex);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllnessBySexAndAge fail",e);
            throw e;
        }

    }

    @SuppressWarnings("unchecked")
    public List<Illness> getIllnessByIdsAndSymptom(String ids, String symptom, Integer value) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Symptom s where i.id=s.illness and i.id in ("+ids+") ");
            sqld.append(" and s.symptom=?1 ");
            sqld.append(" and "+value+" between s.sdown and s.sup ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, symptom);
            List<Illness> list = query.getResultList();
            return list;
        } catch (Exception e) {
            log.error("getIllnessByIdsAndSymptom fail",e);
            throw e;
        }

    }

    @SuppressWarnings("unchecked")
    public List<Illness> getIllnessByPart(String ids, String part) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Parts p where i.id=p.illness and i.id in ("+ids+") and p.part=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, part);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllnessByPart fail",e);
            throw e;
        }
    }

    @SuppressWarnings("unchecked")
    public List<Illness> getIllByIdAndsymptomsYes(
            String symptom,
            String ids,
            Integer value,
            String degree,
            String nature,
            String times) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Symptom s where i.id=s.illness and i.id in("+ids+") and s.symptom='"+symptom+"' ");
            if(StringUtils.hasText(degree)){
                sqld.append(" and s.degree='"+degree+"' ");
            }
            if(StringUtils.hasText(nature)){
                sqld.append(" and s.nature='"+nature+"' ");
            }
            if(StringUtils.hasText(times)){
                sqld.append(" and s.times='"+times+"' ");
            }
            if(value!=null){
                sqld.append(" and "+value+" between s.sdown and s.sup ");
            }
            Query query = entityManager.createQuery(sqld.toString());
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllByIdAndsymptomsYes fail",e);
            throw e;
        }
    }

    /**
     * 返回重要症状
     * */
    public List<Illness> getSymptomsByPart(String ids, String part) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Symptom s where i.id=s.illness and i.id in ("+ids+") and s.parts=?1 and s.isImportant=?2");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, part).setParameter(2, 0);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getSymptomsByPart fail",e);
            throw e;
        }
    }

    public List<Illness> getIllByIdAndsymptomsAndPart(
            String symptom,
            String ids,
            String degree,
            String nature,
            String times,
            String imgurl,
            String part,
            String pastHistory,
            String incentive,
            String medicineHistory,
            Integer isImportant,
            Double tp, String factor) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Symptom s where i.id=s.illness and i.id in ("+ids+") and s.symptom=?1 and s.isImportant=?2");
            int loop = 3;
            if(!StringUtils.isEmpty(medicineHistory)){
                sqld.append(" and s.medicineHistory=?"+loop++);
            }
            if(!StringUtils.isEmpty(pastHistory)){
                sqld.append(" and s.pastHistory=?"+loop++);
            }
            if(!StringUtils.isEmpty(incentive)){
                sqld.append(" and s.incentive=?"+loop++);
            }
            if(!StringUtils.isEmpty(imgurl)){
                sqld.append(" and s.imgurl=?"+loop++);
            }
            if(!StringUtils.isEmpty(degree)){
                sqld.append(" and s.degree=?"+loop++);
            }
            if(!StringUtils.isEmpty(nature)){
                sqld.append(" and s.nature=?"+loop++);
            }
            if(!StringUtils.isEmpty(times)){
                sqld.append(" and s.times=?"+loop++);
            }
            if(!StringUtils.isEmpty(factor)){
                sqld.append(" and s.factor=?"+loop++);
            }
            if(!StringUtils.isEmpty(part)){
                sqld.append(" and s.parts=?"+loop++);
            }
            if(tp!=null){
                sqld.append(" and "+tp+" between s.sdown and s.sup ");
            }
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, symptom).setParameter(2, isImportant);
            loop = 3;
            if(!StringUtils.isEmpty(medicineHistory)){
                query.setParameter(loop++, medicineHistory);
            }
            if(!StringUtils.isEmpty(pastHistory)){
                query.setParameter(loop++, pastHistory);
            }
            if(!StringUtils.isEmpty(incentive)){
                query.setParameter(loop++, incentive);
            }
            if(!StringUtils.isEmpty(imgurl)){
                query.setParameter(loop++, imgurl);
            }
            if(!StringUtils.isEmpty(degree)){
                query.setParameter(loop++, degree);
            }
            if(!StringUtils.isEmpty(nature)){
                query.setParameter(loop++, nature);
            }
            if(!StringUtils.isEmpty(times)){
                query.setParameter(loop++, times);
            }
            if(!StringUtils.isEmpty(factor)){
                query.setParameter(loop++, factor);
            }
            if(!StringUtils.isEmpty(part)){
                query.setParameter(loop++,part);
            }
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllByIdAndsymptomsAndPart fail",e);
            throw e;
        }
    }

    @SuppressWarnings("unchecked")
    public List<Illness> getillNamesBySymptom(String symptom) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i,Symptom s where i.id=s.illness and s.symptom='"+symptom+"' ");
            Query query = entityManager.createQuery(sqld.toString());
            return query.getResultList();
        } catch (Exception e) {
            log.error("getillNamesBySymptom fail",e);
            throw e;
        }
    }
    
    public List<Illness> getIllnessList(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge,
            int pageSize,
            int offset,
            String adminCode) {
        try {
            StringBuffer sqld = new StringBuffer("select distinct i from Illness i ,Symptom s,AgeSelect a where i.id=s.illness and i.id=a.illness ");
            this.makeSql(sqld, illName, parts, levelOneSubject, levelTwoSubject, startTime, endTime, diseaseAge,adminCode);
            if(!StringUtils.isEmpty(symptomName)){
                sqld.append(" and s.symptom='"+symptomName+"' ");
            }
            if(!StringUtils.isEmpty(parts)){
                sqld.append(" and s.parts='"+parts+"' ");
            }
            sqld.append(" order by i.createTime desc");
            Query query = entityManager.createQuery(sqld.toString()).setFirstResult(offset).setMaxResults(pageSize);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getIllnessList fail",e);
            throw e;
        }
    }

    public long getIllnessListCount(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge,
            String adminCode) {
        try {
            StringBuffer sqld = new StringBuffer("select count(distinct i) from Illness i ,Symptom s,AgeSelect a where i.id=s.illness and i.id=a.illness ");
            this.makeSql(sqld, illName, parts, levelOneSubject, levelTwoSubject, startTime, endTime, diseaseAge,adminCode);
            if(!StringUtils.isEmpty(symptomName)){
                sqld.append(" and s.symptom='"+symptomName+"' ");
            }
            if(!StringUtils.isEmpty(parts)){
                sqld.append(" and s.parts='"+parts+"' ");
            }
            Query query = entityManager.createQuery(sqld.toString());
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getIllnessListCount fail",e);
            throw e;
        }
    }
    
    private void makeSql(
            StringBuffer mysql,
            String illName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            String startTime,
            String endTime,
            String diseaseAge,String adminCode){
        if(!StringUtils.isEmpty(diseaseAge)){
            mysql.append(" and a.ageOption in ("+diseaseAge+")");
        }
        if(!StringUtils.isEmpty(illName)){
            mysql.append(" and i.illness='"+illName+"' ");
        }
        if(!StringUtils.isEmpty(levelOneSubject)){
            mysql.append(" and i.levelOneSubject='"+levelOneSubject+"' ");
        }
        if(!StringUtils.isEmpty(levelTwoSubject)){
            mysql.append(" and i.levelTwoSubject='"+levelTwoSubject+"' ");
        }
        if(!StringUtils.isEmpty(adminCode)){
            mysql.append(" and i.author='"+adminCode+"' ");
        }
        mysql.append(" and i.createTime>='"+startTime+"' and i.createTime<='"+endTime+"'");


    }

    @SuppressWarnings("unchecked")
    public List<Illness> getAllIllness() {
        try {
            Query query = entityManager.createQuery("from Illness ");
            return query.getResultList();
        } catch (Exception e) {
            log.error("getAllIllness fail",e);
        }
        return null;
    }

}
